<script setup>
    import projectApi from "@/api/project.js";
    import doctorApi from "@/api/doctor.js";
    import hasBtnPermission from "@/utils/btnPermission.js";
    import {reactive, ref} from 'vue'
    import {ElMessage, ElMessageBox} from "element-plus";
    import { Plus } from '@element-plus/icons-vue'
    import {useTokenStore} from "@/store/token.js";
    const tokenStore = useTokenStore()

    //表格数据
    const list = ref([])
    const total = ref(0)
    //分页信息和搜索条件
    const projectQuery = reactive({
        page: 1,
        limit: 3
    })

    /*function loadData() {
        projectApi.list(projectQuery).then(result => {
            if (result.code == 0) {
                list.value = result.data.records
                total.value = result.data.total
            }
        })
    }*/
    const loadData = () => {
        projectApi.list(projectQuery).then(result => {
            if (result.code == 0) {
                list.value = result.data.records
                total.value = result.data.total
            }
        })
    }

    loadData()

    //根据id删除
    const deleteById = (id) => {
        ElMessageBox.confirm(
            '您确认要删除么?',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                lockScroll: false //防止抖动
            }
        ).then(() => {
            projectApi.deleteById(id).then(result => {
                if (result.code == 0) {
                    ElMessage.success(result.msg)
                    loadData()
                } else {
                    ElMessage.error(result.msg)
                }
            })
        })
    }

    //批量删除
    const ids = ref([])
    const handleSelectionChange = (rows) => {
        console.log('多选：' + rows)
        ids.value = rows.map(row => row.id)
        console.log(ids)
    }

    const deleteAll = () => {
        ElMessageBox.confirm(
            '您确认要删除么?',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                lockScroll: false //防止抖动
            }
        ).then(() => {
            projectApi.deleteAll(ids.value).then(result => {
                if (result.code == 0) {
                    ElMessage.success(result.msg)
                    loadData()
                } else {
                    ElMessage.error(result.msg)
                }
            })
        })
    }

    const project = ref({})
    const dialogFormVisible = ref(false)
    const title = ref()
    //添加、编辑
    const showAddDialog = () => {
        dialogFormVisible.value = true
        project.value = {}
        title.value = '添加'
    }

    const showUpdateDialog = (id) => {
        dialogFormVisible.value = true
        project.value = {}
        title.value = '编辑'
        projectApi.selectById(id).then(result => {
            if (result.code == 0) {
                project.value = result.data
            }
        })
    }

    const addOrUpdate = () => {
        if (project.value.id) {//编辑
            projectApi.update(project.value).then(result => {
                if (result.code == 0) {
                    ElMessage.success(result.msg)
                    dialogFormVisible.value = false
                    loadData()
                } else {
                    ElMessage.error(result.msg)
                }
            })
        } else {
            projectApi.add(project.value).then(result => {
                if (result.code == 0) {
                    ElMessage.success(result.msg)
                    dialogFormVisible.value = false
                    loadData()
                } else {
                    ElMessage.error(result.msg)
                }
            })
        }
    }

    //图片上传
    const handleAvatarSuccess = (result) => {
        project.value.image = result.data
    }

    const headers = ref({
      //携带token传递到后端
      Authorization: tokenStore.token
    })

    //switch
    const handleSwitchChange = (row) => {
        const project = {}
        project.id = row.id
        project.status = row.status
        projectApi.update(project).then(result => {
            if (result.code == 0) {
                ElMessage.success(result.msg)
            } else {
                ElMessage.error(result.msg)
            }
        })
    }

    //查询所有的医美师
    const doctorList = ref([])
    doctorApi.selectAll().then(result => {
        if (result.code == 0) {
            doctorList.value = result.data
        }
    })

    const selectChange = (value) => {
      console.log(value)
    }

    //导入、导出excel
    const exportExcel = () => {
      projectApi.exportExcel().then((result) => {
        let blob = new Blob([result], { type: "application/xlsx" });
        let url = window.URL.createObjectURL(blob);
        const link = document.createElement("a"); // 创建a标签
        link.href = url;
        link.download = "项目列表.xlsx"; // 重命名文件
        link.click();
        URL.revokeObjectURL(url);
      });
    }

    const importExcelSuccess = (result) => {
      if (result.code == 0) {
        ElMessage.success(result.msg)
        loadData()
      }
    }

    const projectList = ref([])
    projectApi.selectAll().then(result => {
      if (result.code == 0) {
        projectList.value = result.data
      }
    })

</script>

<template>
    <el-card>
        <template #header>
            <div class="header">
              <el-button type="success" :icon="Plus" @click="showAddDialog" :disabled="!hasBtnPermission('project:add')">添加</el-button>
              <el-button type="danger" :icon="Delete" @click="deleteAll" :disabled="!hasBtnPermission('project:deleteAll')">批量删除</el-button>
              <el-button type="primary" :icon="Download" @click="exportExcel" :disabled="!hasBtnPermission('project:downLoad')" >导出Excel</el-button>
              <el-upload
                  :icon="Upload"
                  class="inline-block"
                  multiple=""
                  method="post"
                  action="/api/project/importExcel"
                  style="display:inline-block;margin-left: 12px"
                  accept=".xlsx,.xls"
                  :show-file-list="false"
                  :on-success="importExcelSuccess"
                  :headers="headers"
                  name="file">
                <el-button type="primary" :icon="Upload" :disabled="!hasBtnPermission('project:upLoad')">导入Excel</el-button>
              </el-upload>
            </div>
        </template>
        <el-form :inline="true">
            <el-form-item label="项目">
<!--                <el-input v-model="projectQuery.name" placeholder="请输入名字" clearable/>-->
              <el-select clearable v-model="projectQuery.id"  placeholder="请选择项目"
                         style="width: 140px">
                <el-option
                    v-for="project in projectList"
                    :key="project.id"
                    :label="project.name"
                    :value="project.id"
                />
              </el-select>
            </el-form-item>
<!--            <el-form-item label="医美师">-->
<!--                <el-select clearable v-model="projectQuery.doctorId" @change="selectChange" placeholder="请选择医美师"-->
<!--                           style="width: 140px">-->
<!--                    <el-option-->
<!--                        v-for="doctor in doctorList"-->
<!--                        :key="doctor.id"-->
<!--                        :label="doctor.name"-->
<!--                        :value="doctor.id"-->
<!--                    />-->
<!--                </el-select>-->
<!--            </el-form-item>-->

            <el-form-item label="更新时间" :label-width="100">
                <el-date-picker
                    v-model="projectQuery.beginTime"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="开始时间"
                />
                <el-date-picker
                    v-model="projectQuery.endTime"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="结束时间"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="loadData">搜索</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="list" style="width: 100%" ref="multipleTableRef" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"/>
            <el-table-column fixed prop="id" label="ID"/>
            <el-table-column prop="name" label="名字"/>
<!--            <el-table-column prop="doctorId" label="医美师"/>-->
<!--            <el-table-column prop="time" label="项目时间"/>-->
            <el-table-column prop="length" label="项目时长"/>
<!--            <el-table-column prop="maxCount" label="最大人数"/>-->
<!--            <el-table-column prop="count" label="已预约人数"/>-->
            <el-table-column prop="image" label="头像">
                <template #default="scope">
                    <img :src="scope.row.image" style="max-height: 40px; max-width: 120px;"/>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
                <template #default="scope">
                    <el-switch
                        v-model="scope.row.status"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                        :active-value="1"
                        :inactive-value="0"
                        @change="handleSwitchChange(scope.row)"
                        :disabled="!hasBtnPermission('project:sts')"
                    />
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间"/>
            <el-table-column align="center" width="200px" fixed="right" label="Operations">
                <template #default="{ row }">
                    <el-button size="small" type="primary" @click="showUpdateDialog(row.id)" :disabled="!hasBtnPermission('project:update')">编辑</el-button>
                    <el-button size="small" type="danger" @click="deleteById(row.id)" :disabled="!hasBtnPermission('project:delete')">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            v-model:current-page="projectQuery.page"
            v-model:page-size="projectQuery.limit"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @change="loadData"
            style="margin-top: 20px; justify-content: flex-end"
        />
    </el-card>

    <!--添加、编辑弹出框-->
    <el-dialog v-model="dialogFormVisible" :title="title" width="30%" :lock-scroll="false">
        <el-form :model="project">
            <el-form-item label="名字" :label-width="80">
                <el-input v-model="project.name" autocomplete="off" />
            </el-form-item>
<!--            <el-form-item label="医美师" :label-width="80">-->
<!--                <el-select clearable v-model="project.doctorId"  placeholder="请选择医美师"-->
<!--                           style="width: 100%">-->
<!--                    <el-option-->
<!--                        v-for="doctor in doctorList"-->
<!--                        :key="doctor.id"-->
<!--                        :label="doctor.name"-->
<!--                        :value="doctor.id"-->
<!--                    />-->
<!--                </el-select>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="开始时间" :label-width="80">-->
<!--                <el-date-picker-->
<!--                    v-model="project.time"-->
<!--                    type="datetime"-->
<!--                    value-format="YYYY-MM-DD HH:mm:ss"-->
<!--                    placeholder="开始时间"-->
<!--                />-->
<!--            </el-form-item>-->
            <el-form-item label="项目时长" :label-width="80">
                <el-input-number  v-model="project.length" :min="1" :max="100" :step="1" placeholder="项目时长"/>
            </el-form-item>
<!--            <el-form-item label="房间" :label-width="80">-->
<!--                <el-input v-model="project.room" autocomplete="off" />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="最大人数" :label-width="80" >-->
<!--                <el-input-number v-model="project.maxCount" :min="1" :max="50" :step="1" placeholder="最大人数"/>-->
<!--            </el-form-item>-->
            <el-form-item label="头像" :label-width="80">
                <el-upload
                    class="avatar-uploader"
                    action="/api/upload"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :headers="headers">
                    <img v-if="project.image" :src="project.image" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="addOrUpdate">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>

</template>

<style scoped>
    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
</style>